package com.ict.ms.trackPlayBack.service.hive.service;

import com.ict.ms.trackPlayBack.facade.dto.AreaParams;
import com.ict.ms.trackPlayBack.facade.dto.ResultObjWithCount;
import com.ict.ms.trackPlayBack.facade.hive.common.HiveProperGet;
import com.ict.ms.trackPlayBack.facade.hive.helper.HiveDBInterface;
import com.ict.ms.trackPlayBack.facade.model.AreaPlayBack;
import com.ict.ms.trackPlayBack.facade.model.MapFusePlayBackList;
import com.ict.ms.trackPlayBack.facade.model.MapOrigPlayBackList;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenlong on 2017/3/13.
 */
@Service
public class AreaPlayBackService {
    private HiveDBInterface hiveDBInterface=null;

    int Target_ID, Record_UTC_Time, Longitude, Latitude, Direction, Heading,Speed;
    int Orig_Type,Orig_Source;

    Map<String,ArrayList<AreaPlayBack>> m;

    /**
     * 读取配置文件，初始化连接
     */
    private void init(){
        //读取连接hive的配置文件
        HiveProperGet hiveProperGet=new HiveProperGet("/hive.properties");
        hiveDBInterface = new HiveDBInterface(hiveProperGet.getHive_dbname(),hiveProperGet.getHive_ip(), Integer.parseInt(hiveProperGet.getHive_port()),
                hiveProperGet.getHive_user(), hiveProperGet.getHive_psword());

        //连接hive
        hiveDBInterface.connectToDB("hive");
    }

    /**
     *
     * @param areaParams
     * @return
     */
    public ResultObjWithCount areaTrackPlayBack(AreaParams areaParams, int limit, int mode){
        ResultObjWithCount resultObjWithCount=new ResultObjWithCount();

        try{
            init();
            //拼接SQL语句
            String sql="";
            if(mode==0){
                sql = SQLBuilder(areaParams,limit);
                //执行查询
                System.out.println(sql);
                ResultSet res=hiveDBInterface.query1(sql);

                AreaPlayBack areaPlayBack=null;
                m = new HashMap<String,ArrayList<AreaPlayBack>>();
                //对查询结果进行解析
                while (res.next()) {
                    Target_ID = res.getInt(1);
                    Record_UTC_Time = res.getInt(2);
                    Longitude = res.getInt(3);
                    Latitude = res.getInt(4);
                    Direction = res.getInt(5);
                    Heading = res.getInt(6);
                    Speed=res.getInt(7);
                    Orig_Type=res.getInt(8);
                    Orig_Source=res.getInt(9);

                    areaPlayBack=new AreaPlayBack(Target_ID,Record_UTC_Time,Longitude,Latitude,Direction,Heading,Speed);
                    putFuseAdd(Integer.toString(Target_ID),areaPlayBack);
                }

                //关闭连接
                hiveDBInterface.closeDB();

                List<MapFusePlayBackList> mapPlayBackLists = new ArrayList<MapFusePlayBackList>();
                for (Map.Entry<String, ArrayList<AreaPlayBack>> entry : m.entrySet()) {
                    MapFusePlayBackList mapPlayBackList = new MapFusePlayBackList();
                    mapPlayBackList.setNum(Integer.parseInt(entry.getKey()));
                    mapPlayBackList.setPosList(entry.getValue());
                    mapPlayBackLists.add(mapPlayBackList);
                }

                resultObjWithCount.setShipcount(mapPlayBackLists.size());
                resultObjWithCount.setState(1);
                resultObjWithCount.setObj(mapPlayBackLists);
                return resultObjWithCount;
            }else if(mode==1){
                sql = SQLBuilder1(areaParams,limit);
                //执行查询
                System.out.println(sql);
                ResultSet res=hiveDBInterface.query1(sql);

                AreaPlayBack areaPlayBack=null;
                m = new HashMap<String,ArrayList<AreaPlayBack>>();
                //对查询结果进行解析
                while (res.next()) {
                    Target_ID = res.getInt(1);
                    Record_UTC_Time = res.getInt(2);
                    Longitude = res.getInt(3);
                    Latitude = res.getInt(4);
                    Direction = res.getInt(5);
                    Heading = res.getInt(6);
                    Speed=res.getInt(7);
                    Orig_Type=res.getInt(8);
                    Orig_Source=res.getInt(9);

                    areaPlayBack=new AreaPlayBack(Target_ID,Record_UTC_Time,Longitude,Latitude,Direction,Heading,Speed,Orig_Type,Orig_Source);
                    putOrigAdd(Integer.toString(Target_ID),areaPlayBack);
                }

                //关闭连接
                hiveDBInterface.closeDB();

                List<MapOrigPlayBackList> mapOrigPlayBackLists=new ArrayList<MapOrigPlayBackList>();
                for(Map.Entry<String,ArrayList<AreaPlayBack>> entry:m.entrySet()){
                    MapOrigPlayBackList mapOrigPlayBackList=new MapOrigPlayBackList();

                    //原始模式将目标
                    String[] strArray=entry.getKey().split("_");
                    mapOrigPlayBackList.setNum(Integer.parseInt(strArray[0]));
                    mapOrigPlayBackList.setOrigtype(Integer.parseInt(strArray[1]));
                    mapOrigPlayBackList.setOrigSource(Integer.parseInt(strArray[2]));

                    mapOrigPlayBackList.setPosList(entry.getValue());
                    mapOrigPlayBackLists.add(mapOrigPlayBackList);
                }

                resultObjWithCount.setShipcount(mapOrigPlayBackLists.size());
                resultObjWithCount.setState(1);
                resultObjWithCount.setObj(mapOrigPlayBackLists);
                return resultObjWithCount;
            }else{
                return null;
            }
        }catch (Exception e){
            System.out.println("获取区域历史信息失败"+e);
            //关闭连接
            hiveDBInterface.closeDB();
            return null;
        }
    }

    public void putFuseAdd(String key,AreaPlayBack areaPlayBack){
        if(!m.containsKey(key)){
            m.put(key, new ArrayList<AreaPlayBack>());
        }
        m.get(key).add(areaPlayBack);
    }

    public void putOrigAdd(String key,AreaPlayBack areaPlayBack){
        key=key+"_"+areaPlayBack.getTp()+"_"+areaPlayBack.getSo();
        if(!m.containsKey(key)){
            m.put(key, new ArrayList<AreaPlayBack>());
        }
        m.get(key).add(areaPlayBack);
    }

//    /**
//     * 获取指定区域，指定时间段里面的历史船舶列表
//     * @param areaParams
//     * @return
//     */
//    public List<Integer> getIdArray(AreaParams areaParams){
//        try{
//            init();
//            //拼接SQL语句
//            String sql2 = SQLBuilder2(areaParams);
//            //执行查询
//            System.out.println(sql2);
//            ResultSet res2=hiveDBInterface.query1(sql2);
//            List<Integer> list=new ArrayList<Integer>();
//
//            while (res2.next()) {
//                list.add(res2.getInt(1));
//            }
//            System.out.println(list.size());
//            /// TODO: 2017/3/15 关闭连接
//            return list;
//        }catch (Exception e){
//            System.out.println("获取区域历史船总条数失败"+e);
//            /// TODO: 2017/3/15 关闭连接
//            return null;
//        }
//    }

    //接收时间，空间信息，生成查询语句
    private String SQLBuilder(AreaParams areaParams,int limit) {

        String tableName = "l1_target_history_positions_hive";
        String columName = "Target_ID,Record_UTC_Time,Record_UTC_Time,Longitude,Latitude,Direction,Heading,Speed,Orig_Info_Type,Orig_Info_Source";

        StringBuilder builder = new StringBuilder();
        builder.append(" select ");
        builder.append(columName);
        builder.append(" from ");
        builder.append(tableName);

        builder.append(" where Record_UTC_Time > ");
        builder.append(areaParams.getStartTime());
        builder.append(" and Record_UTC_Time < ");
        builder.append(areaParams.getEndTime());

        builder.append(" and Longitude < ");
        builder.append(areaParams.getUrlon());
        builder.append(" and Latitude > ");
        builder.append(areaParams.getLdlat());
        builder.append(" and Latitude < ");
        builder.append(areaParams.getUrlat());
        builder.append(" and Longitude > ");
        builder.append(areaParams.getLdlon());
        builder.append(" order by Record_UTC_Time desc");
        if(limit!=0){
            builder.append(" limit "+limit);
        }
        return builder.toString();
    }

    //接收时间，空间信息，生成查询语句
    private String SQLBuilder1(AreaParams areaParams,int limit) {

        String tableName = "l1_target_history_positions_hive";
        String columName = "Target_ID_Orig,Record_UTC_Time,Record_UTC_Time,Longitude,Latitude,Direction,Heading,Speed,Orig_Info_Type,Orig_Info_Source";

        StringBuilder builder = new StringBuilder();
        builder.append(" select ");
        builder.append(columName);
        builder.append(" from ");
        builder.append(tableName);

        builder.append(" where Record_UTC_Time > ");
        builder.append(areaParams.getStartTime());
        builder.append(" and Record_UTC_Time < ");
        builder.append(areaParams.getEndTime());

        builder.append(" and Longitude < ");
        builder.append(areaParams.getUrlon());
        builder.append(" and Latitude > ");
        builder.append(areaParams.getLdlat());
        builder.append(" and Latitude < ");
        builder.append(areaParams.getUrlat());
        builder.append(" and Longitude > ");
        builder.append(areaParams.getLdlon());
        builder.append(" order by Record_UTC_Time desc");
        if(limit!=0){
            builder.append(" limit "+limit);
        }
        return builder.toString();
    }

//    private String SQLBuilder2(AreaParams areaParams) {
//        StringBuilder builder = new StringBuilder();
//        builder.append(" select ");
//        builder.append(" DISTINCT(Target_ID) ");
//        builder.append(" from ");
//        builder.append(tableName);
//        builder.append(" where ");
//
//        builder.append(" Record_UTC_Time > ");
//        builder.append(areaParams.getStartTime());
//        builder.append(" and Record_UTC_Time < ");
//        builder.append(areaParams.getEndTime());
//
//        builder.append(" and Longitude < ");
//        builder.append(areaParams.getUrlon());
//        builder.append(" and Latitude > ");
//        builder.append(areaParams.getLdlat());
//        builder.append(" and Latitude < ");
//        builder.append(areaParams.getUrlat());
//        builder.append(" and Longitude > ");
//        builder.append(areaParams.getLdlon());
//
//        return builder.toString();
//    }

}